using Microsoft.Extensions.Hosting;

namespace HostingDemo
{
    public class PerformanceMetrics
    {
        private static readonly Random random = new Random();

        public int Processor { get; set; }
        public long Memory { get; set; }
        public long Network { get; set; }

        public override string ToString()
        {
            return $"CPU: {Processor} % ; Memory:{Memory}M ; Network:{Network}M/s";
        }

        public static PerformanceMetrics Create()
        {
            return new PerformanceMetrics { Processor = random.Next(1, 8), Memory = random.Next(10, 100), Network = random.Next(20, 90) };
        }
    }


    public class PerformanceMetricsCollector : IHostedService
    {
        private IDisposable scheduler;

        public Task StartAsync(CancellationToken cancellationToken)
        {
            scheduler = new Timer(callBack, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            scheduler?.Dispose();
            return Task.CompletedTask;
        }


        private static void callBack(object state)
        {
            Console.WriteLine($"{DateTime.Now.ToString()},{PerformanceMetrics.Create().ToString()}");
        }
    }


    
}
